package com.sunbird.crm.servce.impl;

import com.sunbird.crm.base.Vo.RestMessage;
import com.sunbird.crm.base.utils.MD5DES;
import com.sunbird.crm.entity.sys.TUser;
import com.sunbird.crm.servce.LoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

/**
 * @ClassName LoginServiceImpl
 * @Descriptiom TODO
 * @Author Sunbird
 * @Date 2019/8/28 17:46
 * @Version 1.0
 **/
@Service
public class LoginServiceImpl implements LoginService {

    /**
     * @Author Sunbird
     * @Description //登陆
     * @Date  2019/8/28
     * @Param
     * @return
     **/
    @Override
    public RestMessage login(TUser user) {
        RestMessage restMessage =new RestMessage();
        if (user.getLoginCode() !=null && user.getPassword()!=null){

            String msg ="";
            // 1、Subject 实例化对象
            Subject subject  = SecurityUtils.getSubject();
            //2、将用户名和密码封装到token
            UsernamePasswordToken token = null;
            try {
                token = new UsernamePasswordToken(user.getLoginCode(), MD5DES.encrypt(user.getPassword()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            //3、认证
            try {
                subject.login(token);
                restMessage.setMsg_code(200);
                msg ="认证成功";
                restMessage.setMsg(msg);
                return  restMessage;
            }catch (UnknownAccountException e){
                e.printStackTrace();
                msg ="账号不存咋！";
            }catch (IncorrectCredentialsException e){
                e.printStackTrace();
                msg ="密码不正确";
            }catch (AuthenticationException e){
                e.printStackTrace();
                msg ="账号密码不正确";
            }
            restMessage.setMsg_code(500);
            restMessage.setMsg(msg);
            return  restMessage;
        }
        restMessage.setMsg("用户名为空");
        return restMessage;
    }

    @Override
    public RestMessage logout() {
      RestMessage restMessage =new RestMessage();
        Subject subject=  SecurityUtils.getSubject();
      try {
          subject.logout();

      }catch (Exception e){
          restMessage.setMsg("登出异常");
        restMessage.setMsg_code(500);
      }
      restMessage.setMsg_code(200);
        return restMessage;
    }
}
